<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="queryParams.orderNo" clearable style="width: 200px;" placeholder="请输入订单编号"/>
      <el-date-picker v-model="selectDate" value-format="yyyy-MM-dd" format="yyyy年MM月dd日" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="dateChange"/>
      <el-button v-permission="['order:list']" type="primary" icon="el-icon-search" @click="search">查找</el-button>
    </div>
    <el-tabs v-model="currentTab" @tab-click="tabChange">
      <el-tab-pane v-for="tab in tabs" :label="tab.title" :key="tab.status" :name="'tab-'+tab.status"/>
    </el-tabs>
    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中..." border fit highlight-current-row>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.skus" size="small" border>
            <el-table-column align="center" label="编码" prop="sn"/>
            <el-table-column align="center" label="图片">
              <template slot-scope="scope">
                <el-image :src="scope.row.url+'_100_100'" fit="fill" style="width: 100px; height: 100px"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="产品名称" prop="productName" />
            <el-table-column align="center" label="产品规格" prop="skuName" />
            <el-table-column align="center" label="购买数量">
              <template slot-scope="scope">{{ scope.row.buyCount }} {{ scope.row.unit }}</template>
            </el-table-column>
            <el-table-column align="center" label="原价" prop="originalPrice" />
            <el-table-column align="center" label="售价" prop="salePrice" />
            <el-table-column align="center" label="快递费" prop="expressPrice" />
            <el-table-column align="center" label="产品金额" prop="payPrice" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column align="center" width="200" label="订单号" prop="orderNo"/>
      <el-table-column align="center" width="150" label="下单时间" prop="createDate" />
      <el-table-column align="center" label="收货人" width="450">
        <template slot-scope="scope">
          {{ scope.row.consignee }} -- {{ scope.row.phone }}<br>
          {{ scope.row.address }}
        </template>
      </el-table-column>
      <el-table-column align="center" width="110" label="总金额" prop="payPrice"/>
      <el-table-column align="center" width="100" label="配送方式" prop="dispatchName">
        <template slot-scope="scope">
          <el-tag :type="getOrderDispatchClassName(scope.row.dispatchId)" effect="dark">{{ scope.row.dispatchName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="300" label="订单状态">
        <template slot-scope="scope">
          <el-tag :type="getOrderStatusClassName(scope.row.orderStatus)">{{ scope.row.orderStatusName }}</el-tag>&nbsp;&nbsp;&nbsp;
          <el-tag :type="getOrderPayStatusClassName(scope.row.payStatus)">{{ scope.row.payStatusName }}</el-tag>&nbsp;&nbsp;&nbsp;
          <el-tag :type="getOrderExpressStatusClassName(scope.row.expressStatus)">{{ scope.row.expressStatusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <template v-show="scope.row.canCancel">
            <el-button v-permission="['order:cancel']" type="danger" size="mini" @click="toCancel(scope.row)">取消订单</el-button>
          </template>
          <template v-show="scope.row.canConfirmReceiveShopKeeper">
            <el-button v-permission="['order:confirmReceiveShopKeeper']" type="warning" size="mini" @click="confirmReceive(scope.row)">商家确认收货</el-button>
          </template>
          <template v-if="scope.row.canShip">
            <el-button v-permission="['order:ship']" type="primary" size="mini" @click="toShip(scope.row)">发货</el-button>
          </template>
          <el-button v-permission="['order:detail']" type="primary" size="mini" @click="toDetailProduct(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-permission="['order:list']" v-show="total>0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="initList"/>

    <el-dialog :close-on-click-modal="false" :visible.sync="cancelDialogVisible" title="取消订单" @close="closeCancelForm" @open="loadCancelReason">
      <el-form ref="shipForm" :model="cancelForm" status-icon label-position="left" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          {{ cancelForm.orderNo }}
        </el-form-item>
        <el-form-item label="取消原因" prop="reason">
          <el-select v-model="selectReason" placeholder="请选择订单取消原因" @change="changeReason">
            <el-option v-for="(reason, index) in reasons" :key="index" :label="reason.name" :value="reason.value"/>
          </el-select>
          <el-input v-if="showInputReason" v-model="cancelForm.reason" type="textarea" class="margin-top-10" rows="5"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeCancelForm">取消</el-button>
        <el-button v-permission="['order:cancel']" type="primary" @click="confirmCancel">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="shipDialogVisible" title="发货" @open="loadExpresses" @close="closeShip">
      <el-form ref="shipForm" :model="shipForm" status-icon label-position="right" label-width="100px">
        <el-form-item label="发货类型:" prop="type">{{ shipForm.name }}</el-form-item>
        <template v-for="(ex, index) in shipForm.express">
          <div v-if="shipForm.type===1" :key="index">
            <el-form-item :key="'name-'+index" label="快递公司" class="fl">
              <el-select v-model="ex.name" placeholder="请选择快递公司">
                <el-option v-for="express in expresses" :key="express.value" :label="express.name" :value="express.name"/>
              </el-select>
            </el-form-item>
            <el-form-item :key="'no-'+index" label="快递单号" prop="expressNo" class="fl">
              <el-input v-model="ex.expressNo"/>
            </el-form-item>
            <el-form-item v-if="index===0" :key="'plus-'+index" style="width:100px">
              <el-button type="primary" icon="el-icon-plus" circle class="margin-left-10" @click="addExpress"/>
            </el-form-item>
            <el-form-item v-if="index!=0" :key="'minus-'+index" style="width:100px">
              <el-button type="primary" icon="el-icon-minus" circle class="margin-left-10" @click="minusExpress(index)"/>
            </el-form-item>
          </div>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeShip">取消</el-button>
        <el-button v-permission="['order:ship']" type="primary" @click="confirmShip">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { OrderService } from '@/api/OrderService'
import { DictionaryService } from '@/api/CommonService'
import Pagination from '@/components/Pagination'
import { Alert, Notify } from '@/utils/notify'

export default {
  name: 'Order',
  components: { Pagination },
  data() {
    return {
      tabs: [{ title: '全部', status: 0 }, { title: '待发货', status: 1 }, { title: '待退款', status: 2 }, { title: '待收货', status: 3 },
        { title: '未支付', status: 4 }, { title: '已取消', status: 5 }, { title: '已完成', status: 6 }, { title: '已关闭', status: 7 }],
      currentTab: 'tab-0', selectDate: ['', ''],
      queryParams: { pageNo: 1, pageSize: 20, orderNo: undefined, status: undefined, beginTime: undefined, endTime: undefined },
      list: undefined, total: 0, listLoading: true, showInputReason: false,
      cancelDialogVisible: false, cancelForm: { orderNo: undefined, reason: undefined }, reasons: [], selectReason: undefined,
      expresses: [], expressTypes: [{ id: 1, name: '快递/物流' }, { id: 4, name: '自提' }],
      shipDialogVisible: false, shipForm: { orderNo: undefined, type: 0, name: undefined, express: [] }
    }
  },
  created() {
    this.initList()
  },
  methods: {
    dateChange() {
      if (this.selectDate) {
        this.queryParams.beginTime = this.selectDate[0]
        this.queryParams.endTime = this.selectDate[1]
      } else {
        this.queryParams.beginTime = undefined
        this.queryParams.endTime = undefined
      }
    },
    tabChange(tab) {
      this.queryParams.status = tab.index
      this.search()
    },
    initList() {
      this.listLoading = true
      OrderService.listOrder(this.queryParams).then(response => {
        this.list = response.data
        this.total = response.totalCount
        this.listLoading = false
      }).catch(() => { this.listLoading = false })
    },
    search() {
      this.queryParams.pageNo = 1
      this.initList()
    },
    getOrderStatusClassName(status) {
      switch (parseInt(status, 0)) {
        case 100:
          return 'success'
        case 101:
          return 'danger'
        case 102:
          return 'warning'
        case 103:
          return 'info'
        default:
          return ''
      }
    },
    getOrderPayStatusClassName(payStatus) {
      switch (parseInt(payStatus, 0)) {
        case 300:
          return 'info'
        case 301:
          return 'success'
        case 302:
          return 'danger'
        case 303:
          return 'warning'
        default:
          return ''
      }
    },
    getOrderExpressStatusClassName(expressStatus) {
      switch (parseInt(expressStatus, 0)) {
        case 200:
          return 'info'
        case 201:
          return 'warning'
        case 202:
          return 'success'
        case 203:
          return 'success'
        case 204:
          return 'warning'
        case 205:
          return 'warning'
        default:
          return ''
      }
    },
    getOrderDispatchClassName(dispatchId) {
      switch (parseInt(dispatchId, 0)) {
        case 1:
          return 'success'
        case 2:
          return 'info'
        case 3:
          return 'warning'
        default:
          return ''
      }
    },
    toDetailProduct(row) {
      this.$router.push({ path: '/business/order/detail', query: { orderNo: row.orderNo }})
    },
    toCancel(row) {
      this.cancelDialogVisible = true
      this.cancelForm.orderNo = row.orderNo
    },
    confirmCancel() {
      if (!this.cancelForm.reason) {
        Alert.warn(this, '请填写取消订单的原因')
        return
      }
      OrderService.cancelOrder(this.cancelForm).then(() => {
        Notify.success(this, '订单取消成功!')
        this.closeCancelForm()
        this.initList()
      })
    },
    closeCancelForm() {
      this.showInputReason = false
      this.cancelDialogVisible = false
      this.cancelForm.orderNo = undefined
      this.cancelForm.reason = undefined
      this.selectReason = undefined
    },
    loadCancelReason() {
      DictionaryService.listDictionaryByType('cancel_reason').then(result => {
        this.reasons = result
      })
    },
    changeReason() {
      const reasonId = parseInt(this.selectReason)
      if (reasonId === 100) {
        this.showInputReason = true
        this.cancelForm.reason = undefined
      } else {
        this.showInputReason = false
        this.reasons.forEach(reason => {
          if (reasonId === parseInt(reason.value)) {
            this.cancelForm.reason = reason.name
          }
        })
      }
    },
    confirmReceive(row) {
      this.$confirm('您确认已经到退货的产品了吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        OrderService.confirmReceiveShopKeeper(row.orderNo).then(() => {
          Notify.success(this, '收货成功!')
          this.initList()
        })
      }).catch(() => {
        return false
      })
    },
    closeShip() {
      this.shipDialogVisible = false
      this.shipForm.orderNo = undefined
      this.shipForm.express = []
    },
    loadExpresses() {
      this.shipForm.express.push({ name: undefined, expressNo: undefined })
      DictionaryService.listDictionaryByType('express_type').then(result => {
        this.expresses = result
      })
    },
    addExpress() {
      this.shipForm.express.push({ name: undefined, expressNo: undefined })
    },
    minusExpress(index) {
      this.shipForm.express.splice(index, 1)
    },
    toShip(row) {
      this.shipDialogVisible = true
      this.shipForm.orderNo = row.orderNo
      this.shipForm.type = row.dispatchId
      this.shipForm.name = row.dispatchName
    },
    confirmShip() {
      let flag = true
      if (this.shipForm.type === 1) {
        // 快递配送方式，判断快递单号
        this.shipForm.express.forEach(ex => {
          if (!ex.name) {
            Alert.warn(this, '请选择快递/物流公司!')
            flag = false
            return
          }
          if (!ex.expressNo) {
            Alert.warn(this, ex.name + '的运单号不能为空!')
            flag = false
            return
          }
        })
      }
      if (flag) {
        OrderService.shipOrder(this.shipForm).then(() => {
          Notify.success(this, '发货成功!')
          this.initList()
          this.closeShip()
        })
      }
    }
  }
}
</script>
